package com.cndym.adapterForMobile;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.codehaus.jackson.type.TypeReference;

import com.cndym.exception.CndymException;
import com.cndym.exception.ErrCode;
import com.cndym.utils.ConfigUtils;
import com.cndym.utils.HttpClientUtils;
import com.cndym.utils.JsonBinder;
import com.cndym.utils.Utils;

/**
 * Description:
 * Author:cndym
 * Time:2013-01-07 16:46
 */
public class BaseFunction implements IFunction {
    private Logger logger = Logger.getLogger(getClass());
    
    @Override
    public Map<String, String> function(Map<String, String> map) {
        return new HashMap<String, String>();
    }

    public Map<String, String> success() {
        return noBodyReMap(ErrCode.E0000);
    }

    public Map<String, String> success(Map<String, String> paraMap) {
        return bodyReMap(ErrCode.E0000, paraMap);
    }

    public Map<String, String> failure() {
        return noBodyReMap(ErrCode.E0999);
    }

    public Map<String, String> failure(Map<String, String> paraMap) {
        return bodyReMap(ErrCode.E0999, paraMap);
    }

    public Map<String, String> noBodyReMap(String errCode) {
        Map<String, String> reMap = new HashMap<String, String>();
        reMap.put("code", errCode);
        reMap.put("msg", ErrCode.codeToMsg(errCode));
        return reMap;
    }

    public Map<String, String> bodyReMap(String errCode, Map<String, String> paraMap) {
        Map<String, String> reMap = new HashMap<String, String>();
        reMap.put("code", errCode);
        reMap.put("msg", ErrCode.codeToMsg(errCode));
        if (Utils.isNotEmpty(paraMap) && paraMap.size() > 0) {
            reMap.put("result", JsonBinder.buildNonDefaultBinder().toJson(paraMap));
        }
        return reMap;
    }

    public Map<String, String> paraMap(Map<String, String> map) {
        String msg = map.get("msg");
        if (!Utils.isNotEmpty(msg)) {
            return new HashMap<String, String>();
        }
        Map<String, String> paraMap = new HashMap<String, String>();
        try {
            paraMap = JsonBinder.buildNormalBinder().getMapper().readValue(msg, new TypeReference<Map<String, String>>() {});
        } catch (Exception e) {
            throw new CndymException(ErrCode.E3002);
        }
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getKey().equals("msg")) {
                continue;
            }
            paraMap.put(entry.getKey(), entry.getValue());
        }
        return paraMap;
    }


    public Map<String, String> successObj(Map<String, Object> paraMap) {
        return bodyReObjMap(ErrCode.E0000, paraMap);
    }

    public Map<String, String> bodyReObjMap(String errCode, Map<String, Object> paraMap) {
        Map<String, String> reMap = new HashMap<String, String>();
        reMap.put("code", errCode);
        reMap.put("msg", ErrCode.codeToMsg(errCode));
        if (Utils.isNotEmpty(paraMap) && paraMap.size() > 0) {
            reMap.put("result", JsonBinder.buildNonDefaultBinder().toJson(paraMap));
        }
        return reMap;
    }
    
    /**
     * 统计数据收集
     * @param param     全局MAP
     * @param userCode  对应用户USERCODE
     * @param stat      统计数据类型 USER_ACTION_LOGIN 等等
     * @param type      成功1，失败2
     * @return
     */
    public String sendStatLog(Map<String, String> param, String userCode, String stat, int type){
        if(USER_ACTION_REG.equalsIgnoreCase(stat) ||
                USER_ACTION_LOGIN.equalsIgnoreCase(stat))
            return this.sendRegisterOrLoginLog(param, userCode, stat, type);
        
        return null;
        
    }
    
    private String sendRegisterOrLoginLog(Map<String, String> param, String userCode, String stat, int type) {
        String url = Utils.formatStr(ConfigUtils.getValue("STAT_RADER_URL"), "");
        if(Utils.isEmpty(url))return "";
        Map<String, String> resMap = new HashMap<String, String>();
        resMap.put("category", "server");
        resMap.put("product", param.get("platform"));
        resMap.put("version", param.get("softVer"));
        resMap.put("channel", param.get("sid"));
        resMap.put("created", new Date().getTime() + "");
        resMap.put("view", stat);
        resMap.put("user_agent", param.get("machId"));
        resMap.put("client_ip", param.get("ip"));
        resMap.put("referer", "");
        resMap.put("source", "");
        resMap.put("url", "");
        if (type == 1) {
            resMap.put("action", stat + "success");
        } else {
            resMap.put("action", stat + "failure");
        }
        resMap.put("permanent", userCode + System.currentTimeMillis());
        resMap.put("user_hash", userCode);
        StringBuffer buffer = new StringBuffer();
        buffer.append(url).append("?");
        int index = 1;
        for (String key : resMap.keySet()) {
            buffer.append(key).append("=").append(resMap.get(key));
            if (index != resMap.size()) {
                buffer.append("&");
            }
            index++;
        }
        logger.info("发送"+stat+"日志: " + buffer);
        return buffer.toString();
    }
    
    public void sendRegLog(Map<String, String> param, String userCode, String stat, int type){
        try {
            this.sendStatLogAsync(param, userCode, stat, type);
            if(type == 1){
                /*if (param.get("platform").equals(Constants.PLATFORM_IPHONE_CLIENT) || param.get("platform").equals(Constants.PLATFORM_IPHONE_VOICE)) {
                    DataOutActionItem.sendMemberMachineToPush(userCode, param.get("moibleInfo"), "02");
                } else {
                    if (!param.get("platform").equals(Constants.PLATFORM_WAP) && !param.get("platform").equals(Constants.PLATFORM_WEB)) {
                        DataOutActionItem.sendMemberMachineToPush(userCode, param.get("machId"), "01");
                    }
                }*/
            }
        } catch (Exception e) {
        }
    }
    
    /**
     * 
     * @param param
     * @param userCode
     * @param stat
     * @param type
     */
    public void sendStatLogAsync(Map<String, String> param, String userCode, String stat, int type){
        final String url = sendRegisterOrLoginLog(param, userCode, stat, type);
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    HttpClientUtils httpClientUtils = new HttpClientUtils(url);
                    httpClientUtils.httpClientGet();
                }
            }).start();            
        } catch (Exception e) {
        }
    }
    
    //注册
    public static final String USER_ACTION_REG      = "register";
    //登录
    public static final String USER_ACTION_LOGIN    = "login";
    //充值
    public static final String USER_ACTION_RECHARGE = "fill";
    //投注
    public static final String USER_ACTION_TZ       = "income";
    
    public Map<String, String> obj2Str(Map<String, Object> pram){
    	Map<String, String> m = new HashMap<String, String>();
    	for(String str : pram.keySet()){
    		try {
    			m.put(str, (String) pram.get(str));
    		} catch (Exception e) {
    			logger.error(str + "," + e.getMessage());
    		}
    	}
    	return m;
    }
}
